package cn.shujuhai.workflow.service.flow;

import cn.shujuhai.common.pluging.data.ResultVo;
import cn.shujuhai.workflow.domain.FormData;
import cn.shujuhai.workflow.domain.LeaveRequest;
import cn.shujuhai.workflow.service.FormDataService;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class LeaveService {

    private final RuntimeService runtimeService;
    private final TaskService taskService;
    private final FormDataService formDataService;

    public ResultVo<?> applyLeave(LeaveRequest leaveRequest) {
        try {
            // 启动流程实例
            Map<String, Object> variables = new HashMap<>();
            variables.put("initiator", leaveRequest.getInitiator());
            variables.put("leader", leaveRequest.getLeader());
            variables.put("leaveDays", leaveRequest.getLeaveDays());
            variables.put("reason", leaveRequest.getReason());
            String processInstanceId = runtimeService.startProcessInstanceByKey("LeaveProcess", variables).getId();

            // 获取当前任务
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
            if (task != null) {
                return ResultVo.success("请假申请已提交，等待领导审批:" + task.getId());
            } else {
                return ResultVo.failure("未找到当前任务");
            }
        } catch (Exception e) {
            return ResultVo.failure("提交请假申请失败：" + e.getMessage());
        }
    }

    public ResultVo<?> approveLeave1(String taskId, boolean approved) {
        try {
            // 完成任务并传递审批结果
            String status = approved ? "approve" : "reject";
            Map<String, Object> variables = new HashMap<>();
            variables.put("approved", approved);
            variables.put("status", status);
            taskService.complete(taskId, variables);
            return ResultVo.success("审批完成，结果：" + (approved ? "通过" : "不通过"));
        } catch (Exception e) {
            return ResultVo.failure("审批失败：" + e.getMessage());
        }
    }

    public ResultVo<?> approveLeave(FormData formData) {
        try {
            boolean save = this.formDataService.save(formData);
            if (!save) {
                return ResultVo.failure("失败");
            }
            String taskId = formData.getTaskId();

            // 将 JSON 字符串转换为 Map
            Map<String, Object> map = formData.getData();
            map.replaceAll((key, value) -> {
                if (value instanceof String strValue) {

                    // 检查是否为布尔值字符串
                    if ("true".equalsIgnoreCase(strValue)) {
                        return Boolean.TRUE;
                    } else if ("false".equalsIgnoreCase(strValue)) {
                        return Boolean.FALSE;
                    }

                    // 检查是否为数字字符串
                    try {
                        return Integer.parseInt(strValue);
                    } catch (NumberFormatException e) {
                        // 如果不是数字字符串，保持原值
                        return value;
                    }
                }
                // 如果不是字符串，保持原值
                return value;
            });

            taskService.complete(taskId, map);
            return ResultVo.success();
        } catch (Exception e) {
            return ResultVo.failure("审批失败：" + e.getMessage());
        }
    }
}